<?php


namespace app\admin\model;


use think\Db;

class PurchaseModel extends BaseModel
{

    protected $name='purchase';

    protected $pk='purchase_id';


    public static function add($pact,$product){
        $total_num =0;
        if (isset($pact['include'])){
            $pact['delivery_fee'] =0;
            unset($pact['include']);
        }
        if (isset($pact['tax'])){
            $pact['tax_price'] =0;
            unset($pact['tax']);
        }
        $pact['pact_num'] =  self::contractSn();
        $pact['add_time'] = time();
        $pact['due_time'] = strtotime($pact['due_time']);
        $pact['add_user'] = cmf_get_current_admin_id();
        $pact['year'] = date('Y');

        $purchase_id = self::insertGetId($pact);
        foreach ($product as $pk=>&$value){
            $value['purchase_id'] = $purchase_id;
            $value['add_time'] = time();

            $product_info =Db::name("product_info")->alias('pi')
                ->field("pi.*,concat(c.cate_name,'-',s.stuff_name) as stuff_name")
                ->join("dj_stuff s", "s.id = pi.icate", "left")
                ->join("dj_cate c", "c.id = s.cate_id", "left")
                ->where(['pi.pro_id' =>$value['pro_id']])->select();
            foreach ($product_info as $key=>&$value_info){
                $value_part['purchase_id'] =$purchase_id;
                $value_part['pro_id'] =$value_info['pro_id'];
                $value_part['pro_part_id'] =$value_info['id'];
                $value_part['iname'] =$value_info['iname'];
                $value_part['spec'] =$value_info['iwidth'].'mm*'.$value_info['iheight'].'mm*'.$value_info['ithick'].'mm';
                $value_part['stuff_name'] =$value_info['stuff_name'];
                $value_part['total_num'] = $value_info['inumber'] * $value['total_num'];
                $value_part['create_time'] = time();
                PurchaseProductPartModel::add($value_part);
            }
            $total_num += $value['total_num'];
        }
        $res = PurchaseProductOrderModel::add($product);
        self::update(['num'=>$total_num],['purchase_id'=>$purchase_id]);
        return $res;
    }

    /**
     *
     * @param $parem
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function PartUpdataData($parem){

        $type = $parem['type'];//
        $pact = $parem['pact'];//
        $order = $parem['order'];//
        $pact_status_enter = $parem['pact']['status_enter'];//
        $part = $parem['product'];//部件
        $purchase_id = $pact['purchase_id'];
        $pro_id = $part['pro_id'];
        $po_id = $part['po_id'];
        unset($part['po_id']);
        unset($part['pro_id']);
        $this->startTrans();
        try {
            if ($pact_status_enter==2){
                $this->error='全部已入库，请勿进行操作';
                $this->rollback();
                return false;
            }else {
                if (!isset($parem['product']) || !isset($parem['product'][0]['pro_part_id'])){
                    $this->error='请选择产品构件';
                    $this->rollback();
                    return false;
                }
                $this->where(['purchase_id' => $purchase_id])->update([
                    'due_time' => time(),
                    'acceptor_user' => cmf_get_admin_name(),
                    'warehousing_user' => cmf_get_admin_name(),
                    'order_notes' => $pact['order_notes']]);
                $match_actual = 0;
                foreach ($order as $keyp => &$value) {
                    if ($po_id == $value['po_id']) {
                        unset($value['po_id']);
                        if ($type == 1) {
                            ProductSynthesisLogModel::saveDataLog($po_id,$value);
                            $value['status_enter'] = 2;
                        }
                        unset($value['match_actual_num']);
                        $value['remaining_num'] = $value['match_actual'];
                        PurchaseProductOrderModel::update($value, ['po_id' => $po_id]);
                    }
                    $match_actual += $value['total_num'];
                }
                foreach ($part as $key => &$value_part) {
                    if (isset($value_part['pro_part_id'])) {
                        if ($value_part['actual_num'] != 0) {
                            $value_part['create_time'] = time();
                            $partInfo = PurchaseProductPartModel::getProductPartBy(['purchase_id' => $value_part['purchase_id'], 'pro_id' => $value_part['pro_id'], 'pro_part_id' => $value_part['pro_part_id']]);
                            if ($partInfo) {
                                PurchaseProductPartModel::updateDate(['ppp_id' => $partInfo['ppp_id']], $value_part);
                                $ppp_id = $partInfo['ppp_id'];
                            } else {
                                $ppp_id = PurchaseProductPartModel::add($value_part);
                            }
                            ProductPartLogModel::addLog($ppp_id,$value_part);
                        }
                    }
                }
                $match_actual_pur = PurchaseProductOrderModel::where(['purchase_id' => $purchase_id])->sum('match_actual');

                if ($match_actual == $match_actual_pur) {
                    self::update(['status_enter' => 2], ['purchase_id' => $purchase_id]);
                } else {
                    self::update(['status_enter' => 1], ['purchase_id' => $purchase_id]);
                }
            }
            $this->commit();
            return true;
        }catch(\Exception $e) {
            $this->error = '操作失败';
            $this->rollback();
            return false;
        }

    }


    public static function contractSn(){
        $count = self::order('purchase_id DESC')->find();
        $time =date('Y');
        if($count['year']==$time){
            $pact_num = 'CG-'.$time.'-'.str_pad(substr($count['pact_num'],-4)+1, 4, '0', STR_PAD_LEFT);
        }else{
            $pact_num ='CG-'.$time.'-'.str_pad(1, 4, '0', STR_PAD_LEFT);;
        }
        return $pact_num;
    }
}